package com.sichard.waterfullview.request.model;

import android.annotation.SuppressLint;

import com.sichard.waterfullview.RxTransformerHelper;
import com.sichard.waterfullview.net.NetConfig;
import com.sichard.waterfullview.net.RequestManger;
import com.sichard.waterfullview.request.RequestContract;
import com.sichard.waterfullview.request.RequestInterface;
import com.sichard.waterfullview.request.data.WaterfallEntity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.functions.Consumer;

/**
 * <br>类表述：请求业务
 * <br>详细描述：
 * <br><b>Author Caoshichao </b></br>
 * <br><b>Date  2020/4/15</b></br>
 */
public class RequestModel implements RequestContract.Model {
    private int mCurrentPage = 0;

    @SuppressLint("CheckResult")
    @Override
    public void requestWaterfallData(final ResponseCallback callback) {
        mCurrentPage++;
        RequestManger.getInstance().getRetrofit()
                .create(RequestInterface.class)
                .index(NetConfig.KEY, getRequstMap())
                .compose(RxTransformerHelper.<WaterfallEntity>observableIO2Main())
                .subscribe(new Consumer<WaterfallEntity>() {
                    @Override
                    public void accept(WaterfallEntity entities) throws Exception {
                        callback.requestSuccess(entities.hits);

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        callback.onError("请求失败");
                    }
                });
    }

    private Map<String, String> getRequstMap() {
        Map<String, String> requstMap = new HashMap<>();
        requstMap.put("q", "yellow+flowers");
        requstMap.put("image_type", "photo");
        requstMap.put("pretty", "true");
        requstMap.put("page", String.valueOf(mCurrentPage));
        return requstMap;
    }


    public interface ResponseCallback {
        void requestSuccess(List<WaterfallEntity.HitsEntity> result);

        void onError(String errMessage);
    }
}
